import io from 'socket.io-client';

let socket = io('http://192.168.31.161:3000/');
// let socket = io('http://14ch.cn:3000/');
let connection = false;
let gamers = 0;
let id = '';
let gamersdata = [];
let player1 = null;
let idlist = [];
let color = 'white';

export class Connect {
  constructor() {
    // this.socket.emit('',{'message':'i\'m coming!'});
    socket.emit('join');
    socket.on('accept', (data) => {
      connection = true;
      gamers = data.number;
      id = data.id;
      color = data.color;
      // console.log('成功加入游戏,当前人数'+data.number);
    });
    socket.on('check', (data) => {
      // console.log('当前人数' + data.number);
      gamers = data.number;
      gamersdata = data.sync;
      socket.emit('live', {check: data.check, sync: player1});
    });
    socket.on('disconnect', () => {
      connection = false;
    });
    socket.on('reconnect', () => {
      connection = true;
      socket.emit('join');
    })
  }

  getGamers() {
    let templist = [];
    for (let item in gamersdata) {
      let f = false;
      for (let item2 in idlist) {
        if (idlist[item2] === gamersdata[item].id) {
          f = true;
          if (gamersdata[item].id !== id) {
            templist[item2] = gamersdata[item].data;
          }
          break;
        }
      }
      if (!f) {
        idlist.push(gamersdata[item].id);
        templist[idlist.length - 1] = gamersdata[item].data;
      }
    }
    return templist;
  }

  getidnum() {
    return idlist.length;
  }

  getConnection() {
    return connection;
  }

  getId() {
    return id;
  }

  getWords() {
    if (connection) {
      return "当前人数:" + gamers;
    } else {
      return "正在连接中……"
    }
  }

  startGame() {
    socket.emit('start');
  }

  uploaddata(data) {
    player1 = data;
  }

  getColor() {
    return color;
  }
}
